﻿"use strict";

window.ArthurGraus = window.ArthurGraus || {};

ArthurGraus.AdRotator = function (appCode, refresh, div, location) {
    var self = this;
    self.div = div;
    self.appCode = appCode;
    self.refresh = refresh;
    self.location = location;
    self.ads = null;
    self.index = 0;
    self.language = "en-US";
    self.hostWebUrl = "";
    self.initialize = function () {
        self.language = decodeURIComponent(getQuerystring("SPLanguage"));
        self.hostWebUrl = decodeURIComponent(getQuerystring("SPHostUrl"));

        self.getAds();
    };

    self.getAds = function () {
        try {
            var url = "//apps.arthurgraus.nl/Services/AdRotatorService.svc/GetAdsByLocation/{APPCODE}/{LANGUAGE}?l={LOCATION}";

            url = url.replace("{APPCODE}", self.appCode);
            url = url.replace("{LANGUAGE}", self.language);
            url = url.replace("{LOCATION}", self.location);

            $.ajax({
                type: "GET",
                url: url,
                dataType: "jsonp",
                crossDomain: true,
                success: function (results) {
                    self.ads = results;

                    if (self.ads != null && self.ads.length > 1) {
                        setInterval(self.changeAd, self.refresh);
                    }
                    if (self.ads != null) {
                        self.changeAd();
                    }
                },
                error: function (result) {
                }
            });
        }
        catch (error) {

        }
    };

    self.error = function (sender, args) {
    };

    self.changeAd = function () {
        if(self.ads.length >0)
        {
            self.index = Math.floor((Math.random() *  (self.ads.length ) ) );

            var ad = self.ads[self.index];

            if (ad.IsHTML) {
                $('#' + self.div).html(ad.HTML);
            }
            else {
                var urlAdClickHandler = "//apps.arthurgraus.nl/Handlers/AdClick.ashx?ad={adId}&app={app}&source={source}&language={language}&user={user}";

                urlAdClickHandler = urlAdClickHandler.replace("{adId}", self.ads[self.index].AdId);
                urlAdClickHandler = urlAdClickHandler.replace("{app}", self.appCode);
                urlAdClickHandler = urlAdClickHandler.replace("{user}", "");
                urlAdClickHandler = urlAdClickHandler.replace("{source}", encodeURIComponent(self.hostWebUrl));
                urlAdClickHandler = urlAdClickHandler.replace("{language}", encodeURIComponent(self.language));

                $('#' + self.div).html('<a href="' + urlAdClickHandler + '">' +
                                          '<img src="' + self.ads[self.index].ImageUrl + '"/>' +
                                     '</a>');
            }
        }
    };
}

function base64Encode(str) {
    var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var out = "", i = 0, len = str.length, c1, c2, c3;
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += CHARS.charAt(c1 >> 2);
        out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += CHARS.charAt(c3 & 0x3F);
    }
    return out;
}
function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/ /g, '&nbsp;')
            .replace(/\n/g, '<br />');
}


